PIN_OPEN = 0;
PIN_GO = 2;
PIN_IS_OPEN = 1;--外置电平
PIN_LED1_TONER = 5;
PIN_LED2_DRUM = 6;
PIN_LED3_PAPER = 7;
PIN_LED4_READY = "A0";-- ADC输入
gpio.mode(PIN_IS_OPEN,gpio.INT);

gpio.write(PIN_LED1_TONER,gpio.LOW);
gpio.write(PIN_LED2_DRUM,gpio.LOW);
gpio.write(PIN_LED3_PAPER,gpio.LOW);

gpio.mode(PIN_LED1_TONER,gpio.INPUT);
gpio.mode(PIN_LED2_DRUM,gpio.INPUT);
gpio.mode(PIN_LED3_PAPER,gpio.INPUT);

gpio.mode(PIN_OPEN,gpio.OUTPUT);
gpio.mode(PIN_GO,gpio.OUTPUT);
gpio.write(PIN_OPEN,gpio.HIGH);
gpio.write(PIN_GO,gpio.HIGH);
--初始化ADC
adc.force_init_mode(adc.INIT_ADC);

wifi.eventmon.register(wifi.eventmon.STA_CONNECTED,function(t)
end)
wifi.eventmon.register(wifi.eventmon.STA_GOT_IP,function(t)
    --ws_init()
    dofile("printer.lua")
end)
if file.exists("config.lua") then
    dofile("config.lua")
end
dofile("time.lua")
dofile("wifi.lua")
-- dofile("ws.lua")
if file.exists("user.lua") then
    dofile("user.lua")
end
function init()
    local SSID,PWD = wifi.sta.getconfig()
    if string.len(SSID) > 0 then
        wifi_connect(SSID,PWD)
        print("Configed",SSID)
    else
        print("Start Smart Config")
        wifi.sta.clearconfig()
        --wifi_start_smart()
    end

end

init()

LED1=2;LED2=2;LED3=2;LED4=2;OPEN=2;
gpio.trig(PIN_IS_OPEN,"both",function(level,pulse)
    if LED4 == 0 then
        OPEN = level
        udp_send("Open Status Changed "..level)
    end
end)
gpio.trig(PIN_LED1_TONER,"both",function(level,pulse)
    udp_send("LED1 Changed "..level)
end)
gpio.trig(PIN_LED2_DRUM,"both",function(level,pulse)
    udp_send("LED2 Changed "..level)
end)
gpio.trig(PIN_LED3_PAPER,"both",function(level,pulse)
    udp_send("LED3 Changed "..level)
end)
setInterval(function()
    local TADC = adc.read(0);
    local TLED4 = 3;
    if TADC < 30 then
        TLED4 = 0;
    elseif TADC > 600 then
        TLED4 = 1;
    else
        TLED4 = 2;
    end
    if TLED4 ~= LED4 then
        udp_send("LED4 Changed "..TLED4);
        LED4 = TLED4;
    end
end,10)
-- GPIO1 是开关键
function open()
    gpio.write(PIN_OPEN,gpio.LOW);
    setTimeout(function()
        gpio.write(PIN_OPEN,gpio.HIGH);
    end,500)
end
function close()
    gpio.write(PIN_OPEN,gpio.LOW);
    setTimeout(function()
        gpio.write(PIN_OPEN,gpio.HIGH);
    end,4000)
end
function clean()
    if OPEN == 1 then
        close()
        setTimeout(function()clean();end,5000)
    else
       gpio.write(2,gpio.LOW);
       gpio.write(1,gpio.LOW);
       setTimeout(function()
            if LED1 == 1 and LED2 == 1 and LED3 == 1 and LED4 ==0 then
                gpio.write(2,gpio.HIGH);            
            end 
       end,12000) 
    end    
end
